package com.smasher.component.activity

import android.content.Intent
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.smasher.camera.activity.QRcodeActivity
import com.smasher.component.R

class ScanActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_scan)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        findViewById<AppCompatTextView>(R.id.tv_scan).setMovementMethod(LinkMovementMethod.getInstance()); // 允许文本交互
        gotoCamera()
    }

    private fun gotoCamera() {
        val intent = Intent()
        intent.setClass(this@ScanActivity, QRcodeActivity::class.java)
        launcher.launch(intent)
    }

    private fun showText(text: String) {
        findViewById<AppCompatTextView>(R.id.tv_scan).setText(text)
        Log.e(TAG, "showText: $text" )
    }

    private val launcher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == RESULT_OK) {
                val data = result.data
                val resultText = data?.getStringExtra(QRcodeActivity.QRCODE_RESULT)
                if (resultText != null) {
                    showText(resultText)
                }
            }
        }

    companion object{
        const val TAG = "Scan"
    }
}